package com.yff.tuan.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yff.tuan.mapper.CarBindMapper;
import com.yff.tuan.mapper.CarFenceMapper;
import com.yff.tuan.mapper.CarMapper;
import com.yff.tuan.mapper.CarWarnIndexMapper;
import com.yff.tuan.mapper.CarWarnMapper;
import com.yff.tuan.mapper.CarWarningMapper;
import com.yff.tuan.mapper.CoUserMapper;
import com.yff.tuan.mapper.VehicleCheckMapper;
import com.yff.tuan.model.Car;
import com.yff.tuan.model.CarBind;
import com.yff.tuan.model.CarBindExample;
import com.yff.tuan.model.CarFence;
import com.yff.tuan.model.CarWarn;
import com.yff.tuan.model.CarWarnExample;
import com.yff.tuan.model.CarWarning;
import com.yff.tuan.model.CarWarningExample;
import com.yff.tuan.model.CoUser;
import com.yff.tuan.model.VehicleCheck;
import com.yff.tuan.model.VehicleCheckExample;
import com.yff.tuan.model.VehicleCheckExample.Criteria;
import com.yff.tuan.service.VehicleCheckService;
import com.yff.tuan.util.AppSendUtils;
import com.yff.tuan.util.DateUtil;
import com.yff.tuan.util.MathUtil;
import com.yff.tuan.util.Page;

@Component
public class VehicleCheckServiceImpl implements VehicleCheckService{
	@Autowired
	CoUserMapper userMapper;
	@Autowired
	VehicleCheckMapper mapper;
	@Autowired
	CarFenceMapper carFenceMapper;
	@Autowired
	CarBindMapper bindMapper;
	@Autowired
	CarMapper carMapper;
	@Autowired
	CarWarnMapper carWarnMapper;
	@Autowired
	CarWarningMapper carWarningMapper;
	@Autowired
	CarWarnIndexMapper carWarnIndexMapper;
	
	@Override
	public boolean save(VehicleCheck vehicleCheck) {
		Date date = vehicleCheck.getCheckTime();
		if(DateUtil.getFormatDate(date, DateUtil.FORMAT_YYMMDDHHMMSS).equals("2017-01-01 00:00:00") ) {
			return false;
		}
		List<CarFence> carFences = carFenceMapper.selectByProductId(vehicleCheck.getProductId());
		VehicleCheckExample example = new VehicleCheckExample();
		Criteria criteria = example.createCriteria();
		criteria.andProductIdEqualTo(vehicleCheck.getProductId());
		example.setOrderByClause(" id desc limit 1 ");
		List<VehicleCheck> checks = mapper.selectByExample(example);
		if(null != carFences && !carFences.isEmpty()) {
			CarBindExample bindExample = new CarBindExample();
			bindExample.createCriteria().andProductIdEqualTo(vehicleCheck.getProductId());
			List<CarBind> carBinds = bindMapper.selectByExample(bindExample);
			if(null != carBinds && !carBinds.isEmpty()) {
				vehicleCheck.setCarId(carBinds.get(0).getCarId());
			}
			CarBindExample bindExample2 = new CarBindExample();
			bindExample2.createCriteria().andProductIdEqualTo(vehicleCheck.getMatchProductId());
			List<CarBind> carBinds2 = bindMapper.selectByExample(bindExample2);
			Car car = null;
			if(null != carBinds2 && !carBinds2.isEmpty()) {
				vehicleCheck.setMatchCarId(carBinds2.get(0).getCarId());
				car = carMapper.selectByPrimaryKey(carBinds2.get(0).getCarId());
			}
			vehicleCheck = AppSendUtils.getBaiduMap(vehicleCheck);
			String taillight = vehicleCheck.getTaillight();
			boolean isInsert = false;
			if(checks.isEmpty()) {
				vehicleCheck.setOneMile(0.0);
				vehicleCheck.setMiles(0.0);
				vehicleCheck.setState(0);
				isInsert = mapper.insert(vehicleCheck)>0?true:false;
				if(isInsert && null != car) {
					insertCarWarn(taillight, car.getCoUserId(), carBinds.get(0).getCarId(), vehicleCheck.getProductId());
				}
				return isInsert;
			}else {
				boolean isIn = false;
				for(CarFence carFence:carFences) {
					isIn = Double.valueOf(vehicleCheck.getLat().trim()).doubleValue()<carFence.getNorth().doubleValue() 
								&& Double.valueOf(vehicleCheck.getLat().trim()).doubleValue()>carFence.getSouth().doubleValue()  
								&& Double.valueOf(vehicleCheck.getLng().trim()).doubleValue()<carFence.getEast().doubleValue() 
								&& Double.valueOf(vehicleCheck.getLng().trim()).doubleValue()>carFence.getWest().doubleValue();
					
					if(isIn) {
						break;
					}
				}
				
				if(isIn && checks.get(0).getState() ==0) {
					vehicleCheck.setId(checks.get(0).getId());
					vehicleCheck.setState(0);
					if(null == car) {
						vehicleCheck.setMatchCarId(null);
					}
					isInsert = mapper.updateByPrimaryKeySelective(vehicleCheck)>0?true:false;
					if(isInsert && null != car) {
						insertCarWarn(taillight, car.getCoUserId(), carBinds.get(0).getCarId(), vehicleCheck.getProductId());
					}
					return isInsert;
				}
				
				if(isIn && (checks.get(0).getState() ==1 || checks.get(0).getState() ==2) ) {
					vehicleCheck.setState(0);
				}else {
					vehicleCheck.setState(1);
					if(vehicleCheck.getSpeed().doubleValue()==0) {
						vehicleCheck.setState(2);
					}
				}
				
				long time = (vehicleCheck.getCheckTime().getTime() - checks.get(0).getCheckTime().getTime())/1000;
				if(time<0) {
					time = 0;
				}
				double oneMile = vehicleCheck.getSpeed()*0.28*time*1.13/1000;
				double miles = oneMile +checks.get(0).getMiles().doubleValue() ;
				if(checks.get(0).getState() ==0 ){
					miles = 0;
					oneMile = 0;
				}
				
				vehicleCheck.setOneMile(MathUtil.parseDouble(oneMile));
				vehicleCheck.setMiles(MathUtil.parseDouble(miles));
				
				isInsert = mapper.insert(vehicleCheck)>0?true:false;
				if(isInsert && null != car) {
					insertCarWarn(taillight, car.getCoUserId(), carBinds.get(0).getCarId(), vehicleCheck.getProductId());
				}
				return isInsert;
			}
		}else {
			return true;
		}
	}

	@Override
	public Page<VehicleCheck> queryByPage(VehicleCheckExample example, Integer pageNum) {
		int count = mapper.countByExample(example);
		Page<VehicleCheck> page = new Page<VehicleCheck>(pageNum, count);
		List<VehicleCheck> vehicleChecks = mapper.queryByPage(page.getStartIndex(), page.getPageSize());
		page.setList(vehicleChecks);
		return page;
	}
	
	private void insertCarWarn(String taillight,Integer userId,Integer carId ,String productId) {
		try {
			String dx1 = taillight.substring(0, 2);
			String dx2 = taillight.substring(2, 4);
			String dx3 = taillight.substring(4, 6);
			String dx4 = taillight.substring(6, 8);
			String dx5 = taillight.substring(8, 10);
			String dx6 = taillight.substring(10, 12);
			String dx7 = taillight.substring(12, 14);
			String dx8 = taillight.substring(14, 16);
			
			String dy1 = taillight.substring(18, 20);
			String dy2 = taillight.substring(20, 22);
			String dy3 = taillight.substring(22, 24);
			String dy4 = taillight.substring(24, 26);
			String dy5 = taillight.substring(26, 28);
			String dy6 = taillight.substring(28, 30);
			String dy7 = taillight.substring(30, 32);
			String dy8 = taillight.substring(32, 34);
			
			
			int d1= check(dx1, dy1);
			int d2= check(dx2, dy2);
			int d3= check(dx3, dy3);
			int d4= check(dx4, dy4);
			int d5= check(dx5, dy5);
			int d6= check(dx6, dy6);
			int d7= check(dx7, dy7);
			
			double d8= MathUtil.parseDouble(Double.valueOf(Integer.parseInt(dx8,16))/10);
			CoUser coUser = userMapper.selectByPrimaryKey(userId);
			if(coUser.getParentId() != null && coUser.getParentId() != 0) {
				userId = coUser.getParentId();
			}
			
			CarWarnExample example = new CarWarnExample();
			example.createCriteria().andUserIdEqualTo(userId);
			List<CarWarn> carWarns = carWarnMapper.selectByExample(example );
			if(null != carWarns && !carWarns.isEmpty()) {
				Double charge = carWarns.get(0).getCharge();
				Double chargeWarning = carWarns.get(0).getChargeWarning();
				
				if(d1+d2+d3+d4+d5+d6+d7 != 0 || d8 <charge ||d8 <chargeWarning) {
					CarWarning carWarning = new CarWarning();
					carWarning.setCarId(carId);
					carWarning.setCharge(""+d8);
					if(d8 >= chargeWarning) {
						carWarning.setChargeWarning(d8 <charge?1:0);
					}
					carWarning.setChargeAlarm(""+d8);
					carWarning.setChargeAlarmWarning(d8 <chargeWarning?1:0);
					carWarning.setProductId(productId);
					carWarning.setD1(d1);
					carWarning.setD2(d2);
					carWarning.setD3(d3);
					carWarning.setD4(d4);
					carWarning.setD5(d5);
					carWarning.setD6(d6);
					carWarning.setD7(d7);
					carWarning.setWarnDate(new Date());
					
					/*carWarning.setPressureUnder10(pressureUnder10);
					carWarning.setPressureUnder10Warning(pressureUnder10Warning);
					carWarning.setPressureUnder20(pressureUnder20);
					carWarning.setPressureUnder20Warning(pressureUnder20Warning);
					carWarning.setPressureUnder30(pressureUnder30);
					carWarning.setPressureUnder30Warning(pressureUnder30Warning);
					carWarning.setPressureUpper10(pressureUpper10);
					carWarning.setPressureUpper10Warning(pressureUpper10Warning);
					carWarning.setPressureUpper20(pressureUpper20);
					carWarning.setPressureUpper20Warning(pressureUpper20Warning);
					carWarning.setTemperatureUpper10(temperatureUpper10);
					carWarning.setTemperatureUpper10Warning(temperatureUpper10Warning);
					carWarning.setTemperatureUpper20(temperatureUpper20);
					carWarning.setTemperatureUpper20Warning(temperatureUpper20Warning);*/
					CarWarningExample carWarningExample = new CarWarningExample();
					carWarningExample.createCriteria().andProductIdEqualTo(productId);
					List<CarWarning> carWarnings = carWarningMapper.selectByExample(carWarningExample);
					if(null != carWarnings && !carWarnings.isEmpty()) {
						carWarning.setId(carWarnings.get(0).getId());
						carWarningMapper.updateByPrimaryKey(carWarning);
					}else {
						carWarningMapper.insert(carWarning);
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static int  check(String x ,String y ) {
		if(!x.equals("00") && y.equals("00")) {
			return 1;
		}
		return 0;
	}
}
